<template>
	<view class="background">
		<image src="/static/login/bj.jpg" style="width: 100%;" mode="widthFix"></image>
		<view class="container">
			<view class="tip">{{tip}}</view>
			<view v-if="!hasUserInfo" class="row input-phone" style="">
				<zywork-icon type="icon-shouji" size="40" color="#919191"></zywork-icon>
				<text class="text-base" style="margin-left: 15rpx;">+86</text>
				<input style="margin-left: 15rpx;" placeholder="请输入手机号" type="number" v-model="phone"
					pattern="[0-9]*" />
			</view>
			
			<view v-if="!hasUserInfo" class="row input-phone" style="">
				<zywork-icon type="icon-yuechi" size="40" color="#919191"></zywork-icon>
				<input style="margin-left: 15rpx;width: 230rpx;" placeholder="请输入验证码" type="number" v-model="code"  pattern="[0-9]*"/>
				<text class="text-base " :class="getCodeDisabled?'font-color1':'font-color'" style="margin-left: auto;font-size: 28rpx;" @click="getCode">{{getCodeText}}</text>
			</view>
			<view v-if="!hasUserInfo" class="row" style="padding: 20rpx 0rpx;flex: 1;">
				<!-- <text v-show="!isPwd" class="text-base font-color" @click="pwdLogin">密码登录</text>
				<text v-show="isPwd" class="text-base font-color" @click="pwdLogin">验证码登录</text> -->
				<!-- <text v-show="isPwd" class="text-base font-color1" style="margin-left: auto;" @click="retrievePassword">忘记密码?</text> -->
			</view>
			<view v-if="hasUserInfo" class="user-info column align-items-center">
				<image :src="userInfo.wxHeadimgurl?userInfo.wxHeadimgurl:'/static/user-my.jpg'" mode=""></image>
				<text style="margin-top: 30rpx;color: #FFFFFF;">{{userInfo.phonenumber||''}}</text>
			</view>
			<view v-if="!hasUserInfo" class="login-button text-base" style="font-weight: 800;" @click="logins">
				登录
			</view>
			<view v-if="hasUserInfo" class="login-button text-base" @click="navTo('/pages/index/download')" style="font-weight: 800;">
				下载云赚APP
			</view>
			<view v-if="hasUserInfo" class="login-button text-base" @click="removeHasUserInfo"
				style="font-weight: 800;">
				退出登录
			</view>
			<!-- <view class="row" style="margin-top: 30rpx;">
				<text class="font-color1" style="margin-left: auto;">还没有账号?</text>
				<text class="font-color">立即注册</text>
			</view> -->
			<!-- #ifdef APP-PLUS -->
			<view class="font-color1" style="text-align: center;flex: 1;margin-top: 120rpx;">
				——其他登录方式——
			</view>
			<view class="row align-items-center" style="padding: 15rpx 0rpx;" @click="wxLogin">
				<zywork-icon type="icon-weixinzhifu" size="120" color="#07BB0A"></zywork-icon>
			</view>
			<!-- #endif -->
			<!-- <view @click="dis = !dis" class="row align-items-center" style="margin-top: 100rpx;">
				<checkbox value="cb" :checked="dis" color="#6BA9D7" style="transform:scale(0.8);" />
				<text class="font-color1">登录注册代表同意</text>
				<text class="font-color" @click.stop="navTo('/pages/common/common?weburl=https://yunzhuan.zgwlkj.cn/')">服务协议</text>
				<text class="font-color1">和</text>
				<text class="font-color" @click.stop="navTo('/pages/common/common?weburl=https://www.zgwlkj.cn/yunzhuan/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html')">隐私协议</text>
			</view> -->
		</view>
	</view>
</template>

<script>
	import wx from "jweixin-module"
	import popup from '@/components/DuDu-popup/DuDu-popup.vue'
	export default {
		components: {
			popup
		},
		data() {
			return {
				heightTop: 10,
				getCodeText: "获取验证码",
				getCodeDisabled: false,
				dis: false,
				isPwd: false,
				isCheckPwd: true,
				phone: "",
				phoneNumber: "",
				code: "", //验证码
				password: "",
				invitationCode: "", //邀请码
				isShow: true,
				hasUserInfo: false,
				userInfo: {},
				openId: null,
				taskAppId: null,
				taskNoLogin: `您正在进行领取500云豆子任务,请先登陆后领取`,
				taskTip: `云豆任务进行中`
			};
		},
		onLoad(data) {
			console.log('onload', data)
			if (data.rcode) {
				this.invitationCode = data.rcode
			}

			const {
				openId,
				openid,
				taskAppId
			} = data;

			this.openId = openId || openid;
			this.taskAppId = taskAppId;
			console.log('wers', this.taskAppId)
		},
		watch: {
			hasUserInfo(val) {
				if (val) {
					this.taskRun()
				}
			}
		},
		computed: {
			tip() {
				const hasUserInfo = this.hasUserInfo
				return this.taskAppId ? hasUserInfo ? this.taskTip : this.taskNoLogin : null
			}
		},
		created() {
			this.heightTop += uni.getSystemInfoSync().statusBarHeight
			this.phoneNumber = this.$util.PHONE_NUMBER;
			uni.hideLoading()
			this.isWX()
		},
		onShow() {
			this.hasUserInfo = uni.getStorageSync(this.$util.HAS_USER_INFO)
			if (this.hasUserInfo) {
				this.getUserInfo();
				// 三方平台绑定到云赚钱
				// 授予云豆
			}
			
			this.getDownload();
		},
		methods: {
			getDownload() {
				let httpData = {
					vn: 0
				}
				this.$util.doPostForm("/version/versionNumber", httpData, {}, false).then(res => {
					/* res的数据说明
					 * | 参数名称        | 一定返回     | 类型        | 描述
					 * | -------------|--------- | --------- | ------------- |
					 * | versionCode     | y        | int       | 版本号        |
					 * | versionName     | y        | String    | 版本名称      |
					 * | downloadUrl     | y        | String    | 版本下载链接（IOS安装包更新请放跳转store应用商店链接,安卓apk和wgt文件放文件下载链接）  |
					 */
					if (res.data.code == this.$ResponseStatus.OK) {
						// 兼容之前的版本（updateType是新版才有的参数）
						this.versionApp = res.data.data
					} else {}
				});
			},
			getUserInfo() {
				console.log("获取个人信息")
				this.$util.doGet('/user/manager/userInfoList', {}, {}, true).then(res => {
					console.log(res.data)
					if (res.data.code == this.$ResponseStatus.OK) {
						uni.setStorageSync(this.$util.USER_INFO, res.data.data)
						this.userInfo = res.data.data || {}
						this.hasUserInfo = true
						uni.setStorageSync(this.$util.HAS_USER_INFO, this.hasUserInfo)
						this.loginStatus = false;
						uni.hideLoading()
						if (this.weixin) {
							this.getConfig({
								infoTitle: "云赚",
								infoDesc: "分享就送2500云豆/5个环保袋",
								infoLink: this.versionApp.webUrl + '/#/?rcode=' + this.userInfo.rcode,
								infoImg: this.versionApp.webUrl + "/static/icon/LOGO.png"
							})
						}
					} else {
						this.loginStatus = false;
					}
				}).catch(error => {
					console.log(error)
				})
			},
			isWX() {
				let ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					this.weixin = true
				} else {
					this.weixin = false
				}
			},
			async openBind(openId = this.openId) {
				if (openId && this.hasUserInfo) {
					return this.$util.doPostJson(`/media/getMediaOpenidBing`, {
						meidOpenid: openId
					}, {}, true)
				}
				return null
			},
			// 获取积分
			async getPoints() {
				const taskAppId = this.taskAppId;
				if (taskAppId) {
					return this.$util.doPostJson(`/wx/officialSubscribe`, {
						appid: taskAppId,
						openId: this.openId
					}, {}, true);
				}
				return null;
			},
			async taskRun() {
				await this.openBind();
				const {
					data: {
						message,
						code
					}
				} = await this.getPoints();
				if (code === 200) {
					this.taskTip = '您已在“云赚”APP获取500云豆，点击下载或打开APP即可兑兑换袋子'
				} else {
					const prefix = "云豆获取失败了：";
					this.taskTip = prefix + (message || '云豆获取失败');
				}
			},
			getConfig(info) { //自定义分享所需要的参数
				this.$util.getConfig({
					pageUrl: window.location.href //传给后台的参数
				}).then(res => {
					console.log(res.data)
					this.setWxConfig(res.data, info)
				});
			},
			setWxConfig(data, info) {
				data.openTagList = ['wx-open-launch-weapp']
				data.jsApiList = [
					'onMenuShareTimeline', // 分享给好友
					'onMenuShareAppMessage', // 分享到朋友圈
					'updateAppMessageShareData', // 分享给好友1.4
					'updateTimelineShareData' // 分享到朋友圈1.4
				]
				data.debug = false
				wx.config(data);
				wx.ready(function() {
					var shareData = {
						title: info.infoTitle, // 分享标题
						desc: info.infoDesc, // 分享描述
						link: info.infoLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: info.infoImg, // 分享图标
						success: function(res) {}
					};
					//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
					wx.updateTimelineShareData(shareData);
					//自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）
					wx.updateAppMessageShareData(shareData);
				})
				wx.error(function(err) {
					console.log(err, 'error'); // 如果报错打印报错信息

				});
			},
			removeHasUserInfo() {
				uni.setStorageSync(this.$util.HAS_USER_INFO, false)
				this.hasUserInfo = false
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			wxLogin() {
				// #ifdef APP-PLUS
				this.isShow = plus.runtime.isAgreePrivacy()
				if (!this.isShow) {
					return
				}
				// #endif
				// if (this.dis === '' || this.dis !== true) {
				// 	uni.showToast({
				// 		title:"请勾选用户注册协议",
				// 		icon:"none"
				// 	})
				// 	return
				// }
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (~res.provider.indexOf('weixin')) {
							uni.showLoading({
								title: '登陆中'
							})
							uni.login({
								provider: 'weixin',
								success: (loginRes) => {
									if (loginRes.errMsg === 'login:ok') {
										let authResult = loginRes.authResult
										uni.getUserInfo({
											lang: "zh_CN",
											success: (infoRes) => {
												let userInfo = infoRes.userInfo
												console.log(userInfo)
												let data = {
													nickname: userInfo.nickName,
													wxHeadimgurl: userInfo
														.avatarUrl,
													wxCountry: userInfo.country,
													wxOpenid: userInfo.openId,
													wxProvince: userInfo.province,
													wxCity: userInfo.city,
													wxSex: userInfo.gender
												}
												console.log(data)
												this.$util.doPostJson('/user/wxlogin',
													data, {}, false).then(
													userRes => {
														console.log(userRes)
														if (userRes.data.code ==
															this.$ResponseStatus.OK
														) {
															uni.hideLoading()
															uni.setStorageSync(this
																.$util
																.USER_TOKEN_KEY,
																userRes.data
																.data)
															uni.setStorageSync(this
																.$util
																.HAS_USER_INFO,
																true)
															this.queryLable()
														}
													}).catch(error => {
													uni.hideLoading()
													console.log(error)
												})
											},
											fail: () => {
												this.$util.showInfoToast('获取微信用户信息失败')
											}
										})
									}
								},
								fail: (error) => {
									console.log(error)
								}
							});
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			logins() {
				// #ifdef APP-PLUS
				this.isShow = plus.runtime.isAgreePrivacy()
				// #endif
				if (!this.isShow) {
					return
				}
				if (this.loginStatus) {
					return
				}
				// if (this.dis === '' || this.dis !== true) {
				// 	uni.showToast({
				// 		title:"请勾选用户注册协议",
				// 		icon:"none"
				// 	})
				// 	return
				// }
				if (!this.$util.isPhone(this.phone)) {
					this.$util.showInfoToast('请输入正确的手机号')
					return
				}
				if (!this.code && !this.isPwd) {
					this.$util.showInfoToast('请输入验证码')
					return
				}
				let from = {
					phonenumber: this.phone,
					code: this.code,
					inviteeCode: this.invitationCode
				}
				let url = "/user/codeLogin4H5"
				if (this.isPwd) {
					url = "/user/passlogin"
					if (!this.password) {
						this.$util.showInfoToast('请输入密码')
						return
					}
					from = {
						phonenumber: this.phone,
						password: this.password
					}
				}
				uni.showLoading({
					title: "登录"
				})
				this.loginStatus = true;
				this.$util.doPostJson(url, from, {}, false).then(res => {
					console.log(res.data)
					if (res.data.code == this.$ResponseStatus.OK) {
						uni.setStorageSync(this.$util.USER_TOKEN_KEY, res.data.data)
						uni.setStorageSync(this.$util.HAS_USER_INFO, true)
						if (!this.taskAppId) {
							this.navTo('/pages/index/download')
						}
						this.getUserInfo();
					} else {
						this.loginStatus = false;
					}
				}).catch(error => {
					console.log(error)
				})
			},
			getCode() {
				// #ifdef APP-PLUS
				this.isShow = plus.runtime.isAgreePrivacy()
				if (!this.isShow) {
					return
				}
				// #endif
				if (this.getCodeDisabled) {
					return
				}
				if (!this.$util.isPhone(this.phone)) {
					this.$util.showInfoToast('请输入正确的手机号')
					return
				}
				this.getCodeDisabled = true

				let self = this
				let time = 60

				this.$util.doPostForm('/loginApi/SendSMS', {
					phoneNumber: this.phone
				}, {}, false).then(res => {
					if (res.data.code == this.$ResponseStatus.ERROR) {
						this.getCodeDisabled = false
					} else {
						let set = setInterval(function() {
							self.getCodeText = '(' + --time + ')秒后重新获取'
						}, 1000);
						setTimeout(function() {
							self.getCodeDisabled = false;
							self.getCodeText = '获取验证码'
							clearInterval(set)
						}, time * 1000)
					}

				}).catch(error => {
					console.log(error)
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		background-color: #FF4B4A;
	}

	.font-color {
		color: #6BA9D7;
	}

	.font-color1 {
		color: #919191;
	}

	.user-info {
		image {
			width: 200rpx;
			height: 200rpx;
			border-radius: 50%;
		}
	}

	.container {
		width: 95%;
		margin-top: 200rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1;

		.input-phone {
			width: 550rpx;
			background-color: #FFFFFF;
			padding: 15rpx 30rpx;
			border-bottom: solid 1rpx #eeeeee;
			align-items: center;
			margin: 0rpx auto;
			margin-top: 76rpx;
			border-radius: 35rpx;
		}

		.login-button {
			width: 500rpx;
			background-color: #ff643d;
			color: #ffffff;
			height: 100rpx;
			text-align: center;
			line-height: 100rpx;
			border-radius: 50rpx;
			margin: 0rpx auto;
			margin-top: 50rpx;
		}

	}

	.text-lg {
		font-size: 48rpx;
	}

	.text-base {
		font-size: 34rpx;
	}

	.button1 {
		width: 560rpx;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		color: #828282;
		background-color: #FFFFFF;
		margin-top: 20rpx;
		border-radius: 15rpx;
	}

	.button2 {
		width: 560rpx;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		color: #FFFFFF;
		background-color: #08ACEE;
		border-radius: 15rpx;
	}

	.button-press {
		background-color: #d6d6d6;
	}

	.text-view {
		text-align: center;
		padding: 20rpx 20rpx;
	}

	.tip {
		text-align: center;
		font-size: 40rpx;
		color: lawngreen;
		background: rgba(221, 134, 54, .7);
		border-radius: 20rpx;
		margin-bottom: 30rpx;
	}
</style>
